const mysql = require('mysql');
const sqlPoolObj = require('./SQLpool.js');
const sqlPool = sqlPoolObj.sqlpool();

module.exports = {
		getActivityList: function (params,urlParams,callback){
			const page = urlParams.page || 1;
			const size = urlParams.size || 20 ;
			const start = (page - 1) * size;
			const sql = 'SELECT COUNT(id) FROM activity;SELECT * FROM activity limit ?,?;';
			sqlPool.connect(sql, [start, size - 0],function (error, results) {
				if(results){
					var allCount = results[0][0]['COUNT(id)'];
			        var allPage = parseInt(allCount)/20;
			        var pageStr = allPage.toString();
			        if (pageStr.indexOf('.')>0) {
			            allPage = parseInt(pageStr.split('.')[0]) + 1; 
			        }
			        var userList = results[1];
					
					if (error) throw error;
					  	callback("",{msg:'操作成功',totalPages:allPage,currentPage:urlParams.page,data:userList});
				}else{
					if (error) throw error;
					  	callback("",{msg:'操作成功',totalPages:0,currentPage:urlParams.page,data:[]});
				}

			});
		},
		saveActivity:function (params,urlParams,callback){
			
			var sql = 'INSERT INTO activity SET ?'; 
			sqlPool.connect(sql,params,function (error, results) {
				if(error){
					callback(error,{msg:'保存失败'});
				}else{
					callback("",{msg:'保存成功'});
				}
			});
		},
		changeActivity: function(params,callback){
			let sqlValue = ' ';
			let valueArr = [];
			let id = "";
			for($item in params){
				if($item != 'id'){
					sqlValue = sqlValue + $item +'= ?, ';
					valueArr.push(params[$item]);
				}else{
					id = params[$item];
				}
			}
			valueArr.push(id);
			const sql = 'UPDATE activity set '+sqlValue+' WHERE id = ?';
			sqlPool.connect(sql.replace(",  WHERE","  WHERE"),valueArr,function (error, results) {
				if(error){
					callback("",{msg:'保存失败'});
				}else{
					callback("",{msg:'保存成功'});
				}
			});
		},
		getActivityInfo:function(paramObj,callback){
			const sql = 'SELECT * FROM activity where id = ?;';
			sqlPool.connect(sql,[paramObj.id],function (error, results) {
				if(results){
					if (error) throw error;
					  	callback("",results[0]);
				}else{
					if (error) throw error;
					  	callback("",[]);
				}
			});
		},
		exportActivityList : function (params,callback){
			const sql = 'SELECT * FROM activity';
			sqlPool.connect(sql,function (error, results) {
				if(results){
					if (error) throw error;
					  	callback("",results);
				}else{
					if (error) throw error;
					  	callback("",[]);
				}
			});
		},
};